﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using CiStatus.CiStatusAddIn.Logic.PluginInterfaces;

namespace CiStatus.CiStatusAddIn.Logic
{
    public class PluginFinder
    {
        private readonly string _path;
        private string[] _files;

        public PluginFinder(string path)
        {
            _path = path;
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainAssemblyResolve;
        }

        Assembly CurrentDomainAssemblyResolve(object sender, ResolveEventArgs args)
        {
            var parts = args.Name.Split(Convert.ToChar(","));
            var fileName = parts[0].Trim() + ".dll";
            var file = _path + fileName;
            if (_files.Contains(file))
            {
               // var bytes = File.ReadAllBytes(file);
                return Assembly.LoadFrom(file);
            }
            return null;
        }

        public IList<ICiPollerFactory> Find()
        {
            var factories = LoadPluginFactories();
            return factories;
        }

        public IList<ICiPollerFactory> LoadPluginFactories()
        {
            var factories = new List<ICiPollerFactory>();

            _files = Directory.GetFiles(_path);
            foreach (var currentFile in _files)
            {
                try
                {
                    var bytes = File.ReadAllBytes(currentFile);
                    var assembly = Assembly.LoadFrom(currentFile);
                    foreach (var type in assembly.GetTypes())
                    {
                        if (typeof(ICiPollerFactory).IsAssignableFrom(type))
                        {
                            factories.Add((ICiPollerFactory)Activator.CreateInstance(type));
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            return factories;
        }
    }
}
